import Vue from 'vue'
import Vuex from 'vuex'
import cookie from 'vue-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {
      name: window.localStorage.getItem('user') == null ? '未登录' : JSON.parse(window.localStorage.getItem('user' || '[]')).name,
      username: window.localStorage.getItem('user') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).username
    },
    adminMenus: [],
    homework: {
      username: cookie.get('username'),
      name: cookie.get('name'),
      su: 0,
      token: null
    }
  },
  mutations: {
    initAdminMenu (state, menus) {
      state.adminMenus = menus
    },
    login (state, data) {
      state.user = data
      window.localStorage.setItem('user', JSON.stringify(data))
    },
    logout (state) {
      // 注意不能用 null 清除，否则将无法判断 user 里具体的内容
      state.user = []
      window.localStorage.removeItem('user')
      state.adminMenus = []
    },
    clearhomelist (state) {
      state.homework.username = ''
      state.homework.name = ''
      state.homework.name = ''
      state.homework.su = 0
      state.homework.token = ''
      cookie.delete('token')
      cookie.delete('name')
      cookie.delete('su')
      cookie.delete('username')
    },
    homeworkinit (state, res) {
      state.homework.username = res.username
      state.homework.name = res.name
      state.homework.su = res.su
      state.homework.token = res.token
      cookie.set('token', res.token)
      cookie.set('name', res.name)
      cookie.set('su', res.su)
      cookie.set('username', res.username)
    }
  },
  actions: {
  }
})
